//开启服务器
const express = require('express');

const app = express();
app.listen(3000, () => {
    console.log('开启');
})
//引入path
const path = require('path')
//连接mysql数据库
const mysql = require('mysql');


const con = mysql.createConnection({
    host: 'localhost',
    port: '3306',
    user: 'root',
    password: 'root',
    database: 'demo'

})
con.connect();


//渲染register
app.get('/register', (req, res) => {
    res.sendFile(path.join(__dirname, 'register.html'))
})
//渲染login
app.get('/login', (req, res) => {
    res.sendFile(path.join(__dirname, 'login.html'))
})

//post 接参
app.use(express.urlencoded({ extended: false }));

//注册
app.post('/register', (req, res) => {
    let { username, password } = req.body;
    // 判断用户名是否存在
    function fn() {
        return new Promise((resolve, reject) => {
            let sql = `select *from haha where username='${username}'`;
            con.query(sql, (err, result) => {
                if (err) {
                    res.send({ code: 500, msg: err });
                    return;
                }
                // 判断用户名是否存在

                if (result.length > 0) {
                    res.send({ code: 400, msg: '用户名已存在' });
                    return;
                }
                resolve({ username, password });
            })
        })
    }

    async function shi() {
        let { username, password } = await fn();

        // 不存在添加到表中
        let sql = `insert into haha (username,password) values ('${username}','${password}')`

        con.query(sql, (err, result) => {
            if (err) {
                res.send({ code: 500, msg: err });
                return;
            }

            if (result.insertId > 0) {
                res.send({ code: 200, msg: '注册成功' })
            } else {
                res.send({ code: 400, msg: '请稍后再试' })
            }

        })
    }
    shi();
})

//登录
app.post('/login', (req, res) => {
    let { username, password } = req.body;
    // 判断用户名密码是否正确
    let sql = `select * from haha where username = '${username}' and password = '${password}'`;
    console.log(sql);
    con.query(sql, (err, result) => {
        if (err) {
            res.send({ code: 500, msg: err });
            return;
        }
        // 判断用户是否存在
        if (result.length > 0) {
            res.send({ code: 200, mag: '登录成功' });
            return;
        }
        res.send({ code: 400, msg: '用户名密码错误' });
    })

})



